# encoding: utf-8

class ArticleApi < Grape::API
  helpers ::ToolKit
  prefix :articles

  get do
    data, count=Article.paginate(params[:start], params[:end])
    paginate_result data, count, params[:start]
  end

  post do
    p @current_user
    article = Article.create! title: params[:title], content: params[:content], user: @current_user

  end

  resource ':id' do
    after_validation do
      @article = Article.where(id: params[:id]).first
    end

    get do
      error!({message: '此博文不存在！'}.as_json, 404) unless @article
      @article.views+=1
      @article.save!
      @article.safe_attributes
    end

    put do
      require_authorized!

      @article.content = params[:content]
      @article.title = params[:title]
      @article.save!
      @article.safe_attributes
    end

    delete do
      require_authorized!

      @article.enable = false
      @article.save!
    end
  end
end